<?php
namespace Api\Utils;

/**
 * Class ArrayObject
 * @package Api\Utils
 * @author Steffen Brem <steffenbrem@gmail.com>
 */
class ArrayObject implements \ArrayAccess, \IteratorAggregate
{
    protected $storage = array();

    /**
     * @param array $storage
     */
    public function __construct(array $storage)
    {
        foreach ($storage as $k => $i)
        {
            $this->offsetSet($k, $i);
        }
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->storage);
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        if (is_array($value))
        {
            $value = new self($value);
        }

        if ($value === null)
        {
            $this->storage[] = $value;
        }
        else
        {
            $this->storage[$offset] = $value;
        }
    }

    /**
     * @param mixed $offset
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        if (!isset($this->storage[$offset]))
        {
            return null;
        }

        return $this->storage[$offset];
    }

    /**
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->storage[$offset]);
    }

    /**
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        unset($this->storage);
    }

    /**
     * @return array
     */
    public function getStorage()
    {
        return $this->storage;
    }
}